最后一遍-L11-Container With Most Water
/**
* 11. Container With Most Water
*
*
* Given n non-negative integers a1, a2, ..., an , where each represents a point
* at coordinate (i, ai). n vertical lines are drawn such that the two endpoints
* of line i is at (i, ai) and (i, 0). Find two lines, which together with
* x-axis forms a container, such that the container contains the most water.
*
* The above vertical lines are represented by array [1,8,6,2,5,4,8,3,7]. In
* this case, the max area of water (blue section) the container can contain is
* 49.
*
*
*
* Example:
*
* Input: [1,8,6,2,5,4,8,3,7] Output: 49
*
* Note: You may not slant the container and n is at least 2.
*
*
**/
使用什么方式解决问题? array two point 遇到的问题,如何确定循环时候的变量? 怎么进一步的优化,写代码的方式,尽可能的清楚明白的编写,不要炫技,写的清楚明白,对自己编写是有好处的
代码:
public class L11 {
public static void main(String[] args) {
System.out.println(L11.maxArea(new int[] {1,8,6,2,5,4,8,3,7}));
}
public static int maxArea(int[] height) {
int from=0,to=height.length-1;
int result=0;
while(from<to){
int left=height[from],right=height[to];
int cur = Math.min(left,right) *(to-from);
result= cur>result?cur:result;
if(left>right){
to--;
while (height[to] < right) to--;
}else{
from++;
while (height[from] < left) from++;
}
}
return result;
}
}